// axios二次封装
import axios from 'axios'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'
import router from '@/router'



const request = axios.create({
  baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
})
// 请求拦截器
request.interceptors.request.use(

  (config) => {
    // 放行登录
    if (config.url.includes('/login')) {
      return config
    }

    // 其他请求
    const userStore = useUserStore()
    const token = userStore.getUserInfo.token
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => { return Promise.reject(error) }
)

// 响应拦截器
request.interceptors.response.use(
  (response) => {
    return response.data
  },
  (error) => {
    ElMessage.error(error.response.data.msg)
    // token过期
    if (error.response.status === 401) {
      useUserStore().clearUserInfo
      router.replace('/login')
    }
    return Promise.reject(error)
  }
)

// 导出axios实例
export default request
